'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { usePathname } from 'next/navigation';
import { useSession, signOut } from 'next-auth/react';
import {
  HomeIcon,
  DocumentDuplicateIcon,
  ChartBarIcon,
  UserIcon,
  BellIcon,
  ClipboardDocumentListIcon,
  PlusIcon,
  Cog6ToothIcon,
  ArrowRightOnRectangleIcon,
  XMarkIcon,
  ExclamationCircleIcon,
} from '@heroicons/react/24/outline';
import {
  HomeIcon as HomeIconSolid,
  DocumentDuplicateIcon as DocumentIconSolid,
  ChartBarIcon as ChartIconSolid,
  UserIcon as UserIconSolid,
  BellIcon as BellIconSolid,
  ClipboardDocumentListIcon as ClipboardIconSolid,
} from '@heroicons/react/24/solid';
import { cn } from '@/lib/utils';
import useBreakpoint from '@/hooks/use-breakpoint';

const navigation = [
  { 
    name: '首页', 
    href: '/dashboard', 
    icon: HomeIcon, 
    activeIcon: HomeIconSolid 
  },
  { 
    name: '项目', 
    href: '/project', 
    icon: DocumentDuplicateIcon, 
    activeIcon: DocumentIconSolid 
  },
  { 
    name: '任务', 
    href: '/task', 
    icon: ClipboardDocumentListIcon, 
    activeIcon: ClipboardIconSolid 
  },
  { 
    name: '统计', 
    href: '/stats', 
    icon: ChartBarIcon, 
    activeIcon: ChartIconSolid 
  },
];

export default function MobileNavbar() {
  const pathname = usePathname();
  const { isMobile } = useBreakpoint();
  const { data: session, status } = useSession();
  const isAuthenticated = status === 'authenticated';
  const [mounted, setMounted] = useState(false);
  const [showUserMenu, setShowUserMenu] = useState(false);
  const [hasError, setHasError] = useState(false);
  
  // 客户端渲染后才能确定设备类型
  useEffect(() => {
    try {
      setMounted(true);
    } catch (error) {
      console.error('移动导航栏挂载错误:', error);
      setHasError(true);
    }
  }, []);
  
  // 点击页面其他区域时关闭用户菜单
  useEffect(() => {
    try {
      const handleClickOutside = (event: MouseEvent) => {
        const userMenu = document.getElementById('mobile-user-menu');
        const userMenuButton = document.getElementById('mobile-user-menu-button');
        const userMenuOverlay = document.getElementById('mobile-user-menu-overlay');
        
        if (
          userMenu && 
          userMenuButton && 
          !userMenu.contains(event.target as Node) && 
          !userMenuButton.contains(event.target as Node) &&
          event.target !== userMenuOverlay
        ) {
          setShowUserMenu(false);
        }
      };
      
      document.addEventListener('mousedown', handleClickOutside);
      return () => {
        document.removeEventListener('mousedown', handleClickOutside);
      };
    } catch (error) {
      console.error('添加点击事件处理器失败:', error);
    }
  }, []);

  // 处理登出
  const handleSignOut = () => {
    try {
      signOut({ callbackUrl: '/' });
      setShowUserMenu(false);
    } catch (error) {
      console.error('登出失败:', error);
      // 即使出错也关闭菜单
      setShowUserMenu(false);
    }
  };
  
  // 如果不是移动设备或者尚未挂载，则不显示
  if (!mounted || !isMobile) {
    return null;
  }
  
  // 如果当前页面是登录或注册页面，不显示导航栏
  if (pathname.startsWith('/auth/')) {
    return null;
  }

  // 渲染用户头像或默认图标
  const renderUserAvatar = () => {
    try {
      return session?.user?.image ? (
        <Image
          src={session.user.image}
          alt={session.user.name || 'User'}
          width={28}
          height={28}
          className="h-full w-full object-cover"
        />
      ) : (
        <UserIcon className="h-5 w-5 text-white" aria-hidden="true" />
      );
    } catch (error) {
      console.error('渲染用户头像失败:', error);
      return <UserIcon className="h-5 w-5 text-white" aria-hidden="true" />;
    }
  };
  
  return (
    <>
      {/* 用户菜单遮罩层 - 添加动画效果 */}
      {showUserMenu && isAuthenticated && (
        <div 
          id="mobile-user-menu-overlay" 
          className="fixed inset-0 bg-black/30 z-40 animate-fadeIn"
          onClick={() => setShowUserMenu(false)}
          aria-hidden="true"
        />
      )}

      {/* 用户菜单弹出层 - 添加动画和阴影效果 */}
      {showUserMenu && isAuthenticated && (
        <div
          id="mobile-user-menu"
          className="fixed bottom-20 right-4 z-50 w-64 origin-bottom-right rounded-lg bg-white py-2 shadow-xl ring-1 ring-black ring-opacity-5 focus:outline-none animate-slideUp"
          role="dialog"
          aria-modal="true"
          aria-labelledby="user-menu-heading"
        >
          <div className="border-b border-gray-100 pb-2">
            <div className="px-4 py-2">
              <div className="flex items-center">
                <div className="h-10 w-10 rounded-full overflow-hidden bg-gray-100 mr-3">
                  {hasError ? (
                    <div className="h-full w-full flex items-center justify-center bg-gray-200">
                      <ExclamationCircleIcon className="h-6 w-6 text-gray-400" />
                    </div>
                  ) : session?.user?.image ? (
                    <Image
                      src={session.user.image}
                      alt={session.user.name || '用户'}
                      width={40}
                      height={40}
                      className="h-full w-full object-cover"
                      onError={() => setHasError(true)}
                    />
                  ) : (
                    <div className="h-full w-full flex items-center justify-center">
                      <UserIcon className="h-6 w-6 text-gray-400" />
                    </div>
                  )}
                </div>
                <div className="flex-1 min-w-0">
                  <p id="user-menu-heading" className="text-sm font-medium text-gray-900 truncate">
                    {session?.user?.name || '用户'}
                  </p>
                  <p className="text-xs text-gray-500 truncate">
                    {session?.user?.email || ''}
                  </p>
                </div>
                <button 
                  type="button" 
                  className="p-1 rounded-full text-gray-400 hover:bg-gray-100"
                  onClick={() => setShowUserMenu(false)}
                  aria-label="关闭菜单"
                >
                  <XMarkIcon className="h-5 w-5" />
                </button>
              </div>
            </div>
          </div>
          
          <nav className="py-1">
            <Link
              href="/profile"
              className="flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
              onClick={() => setShowUserMenu(false)}
            >
              <UserIcon className="mr-3 h-5 w-5 text-gray-500" />
              个人资料
            </Link>
            <Link
              href="/settings"
              className="flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
              onClick={() => setShowUserMenu(false)}
            >
              <Cog6ToothIcon className="mr-3 h-5 w-5 text-gray-500" />
              设置
            </Link>
          </nav>
          
          <div className="py-1 border-t border-gray-100">
            <button
              className="flex w-full items-center px-4 py-2 text-sm text-red-600 hover:bg-gray-100"
              onClick={handleSignOut}
              aria-label="退出登录"
            >
              <ArrowRightOnRectangleIcon className="mr-3 h-5 w-5" />
              退出登录
            </button>
          </div>
        </div>
      )}
    
      <div className="fixed bottom-0 left-0 z-40 w-full h-16 bg-white border-t border-gray-200 pb-safe">
        <div className="grid h-full grid-cols-5">
          {navigation.map((item) => {
            const isActive = pathname === item.href || pathname.startsWith(`${item.href}/`);
            const IconComponent = isActive ? item.activeIcon : item.icon;
            
            return (
              <Link
                key={item.name}
                href={item.href}
                className="inline-flex flex-col items-center justify-center px-5 hover:bg-gray-50"
                aria-current={isActive ? 'page' : undefined}
              >
                <IconComponent
                  className={cn(
                    isActive ? 'text-[var(--primary-color)]' : 'text-gray-500',
                    'w-6 h-6'
                  )}
                  aria-hidden="true"
                />
                <span 
                  className={cn(
                    'text-xs mt-1',
                    isActive ? 'text-[var(--primary-color)]' : 'text-gray-500'
                  )}
                >
                  {item.name}
                </span>
              </Link>
            );
          })}
          
          {/* 创建/用户按钮 */}
          {isAuthenticated ? (
            <button
              id="mobile-user-menu-button"
              className="inline-flex flex-col items-center justify-center px-5 hover:bg-gray-50 relative"
              onClick={() => setShowUserMenu(!showUserMenu)}
              {...(showUserMenu ? {'aria-expanded': 'true'} : {'aria-expanded': 'false'})}
              aria-haspopup="dialog"
              aria-label="打开用户菜单"
            >
              <div className={cn(
                "h-7 w-7 rounded-full overflow-hidden flex items-center justify-center transition-transform duration-200",
                showUserMenu ? "ring-2 ring-[var(--primary-color)] scale-110" : "bg-[var(--primary-color)]"
              )}>
                {renderUserAvatar()}
              </div>
              <span className={cn(
                "text-xs mt-1",
                showUserMenu ? "text-[var(--primary-color)]" : "text-gray-500"
              )}>我的</span>
            </button>
          ) : (
            <Link
              href="/project/new"
              className="inline-flex flex-col items-center justify-center px-5 hover:bg-gray-50"
              aria-label="创建新项目"
            >
              <div className="bg-[var(--primary-color)] rounded-full p-1">
                <PlusIcon className="h-5 w-5 text-white" aria-hidden="true" />
              </div>
              <span className="text-xs mt-1 text-gray-500">创建</span>
            </Link>
          )}
        </div>
      </div>
    </>
  );
} 